package com.example.cores_activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.cores_activity.utils.DateUtil;

public class RequestActivity extends AppCompatActivity implements View.OnClickListener {

    static private String msg = "有内鬼，终止交易";
    private ActivityResultLauncher<Intent> resultRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_request);

        TextView tv_res = findViewById(R.id.tv_res);

        TextView tv_req = findViewById(R.id.tv_req);
        String content = "发送：" + msg;
        tv_req.setText(content);

        findViewById(R.id.btn_req).setOnClickListener(this);


        // 注册跳转结果，定义回调函数处理结果
        resultRegister = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result == null || result.getResultCode() != Activity.RESULT_OK) return;

            Intent intent = result.getData();
            if (intent == null) return;

            Bundle bundle = intent.getExtras();
            if (bundle == null) return;

            String reqTime = bundle.getString("req_time");
            String reqContent = bundle.getString("req_content");

            // 响应的文本显示
            String format = String.format("收到回复：%s\n时间：%s", reqTime, reqContent);
            tv_res.setText(format);
        });

    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(this, ResponseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("req_time", DateUtil.getNowTime());
        bundle.putString("req_content", msg);
        intent.putExtras(bundle);
        // 执行行为
        resultRegister.launch(intent);
    }
}